package com.itany.servlet;

import com.alibaba.fastjson.JSON;
import com.itany.entity.User;
import com.itany.service.UserService;
import com.itany.service.impl.UserServiceImpl;
import com.itany.util.ResponseResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * Author：汤小洋
 * Date：2022-11-15 9:42
 * Description：<描述>
 */
@WebServlet("*.user")
public class UserServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getServletPath();
        if("/findAll.user".equals(path)){
            findAll(req,resp);
        }else if("/deleteById.user".equals(path)){
            deleteById(req,resp);
        }
    }

    private void deleteById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        int id = Integer.parseInt(req.getParameter("id"));
        userService.removeById(id);

        resp.setContentType("application/json;charset=utf8");
        PrintWriter out = resp.getWriter();
        out.print(JSON.toJSONString(ResponseResult.success()));
        out.close();
    }

    private void findAll(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<User> list = userService.findAll();

        resp.setContentType("application/json;charset=utf8");
        PrintWriter out = resp.getWriter();

        ResponseResult result = ResponseResult.success(list);
        out.print(JSON.toJSONString(result));
        out.close();
    }
}
